package com.bjian.CodeSandBox.controller;

import com.bjian.CodeSandBox.codeSandbox.CodeSandbox;
import com.bjian.CodeSandBox.codeSandbox.impl.DockerCodeSandboxImpl;
import com.bjian.CodeSandBox.codeSandbox.model.ExecuteCodeRequest;
import com.bjian.CodeSandBox.codeSandbox.model.ExecuteCodeResponse;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/")
public class MainController {

    //定义鉴权请求头和密匙
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "BJOJAPI_0101SfAc";

    @Resource
    private DockerCodeSandboxImpl dockerCodeSandboxImpl;

    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request, HttpServletResponse response) {
        if (executeCodeRequest == null) {
            throw new RuntimeException("参数不存在");
        }
        String header = request.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_SECRET.equals(header)){
            response.setStatus(403);
            return null;
        }
        ExecuteCodeResponse executeCodeResponse = dockerCodeSandboxImpl.executeCode(executeCodeRequest);
        return executeCodeResponse;
    }

}
